# -*- coding: utf-8 -*-
'''
This is the main module of the both to be used for including new
templates on some categories
'''
__version__ = "$Revision 0.1.0 $"

import login
import wikipedia
import pagegenerators
import catlib
import re
import values
import logging
import os



def initiate_logger():
    '''
    This function initiates the logger class. To be used for 
    saving the outputs.
    '''
    
    logger = logging.getLogger("Logging ThimBorg execution")
    logger.setLevel(values.LOGLEVEL)
    #Remove log file if exists. Avoid to create a big file
    if os.path.exists(values.LOGFILE):
        os.remove(values.LOGFILE)
    # create file handler which logs even debug messages
    fileh = logging.FileHandler(values.LOGFILE)
    fileh.setLevel(logging.DEBUG)
    
    # create formatter and add it to the handlers
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s -" +
                                  " %(message)s")
    fileh.setFormatter(formatter)
    # add the handlers to logger
    logger.addHandler(fileh)

    return logger


def scan_templates(text, template):
    '''
    This function simply detects if there is a template inside the wikipedia 
    page
    
    Key Parameters
    
    \Text     is unicode input with a wikipedia page
    \Template is the template name related to the category.
    '''
    return re.search(template, text)
def act_on_page(logger, page, template):
    '''
    This function will act over a given page. Ideally the page
    will changed and the template introduced if not present.
    '''
    if not page.isRedirectPage():
        text_page = page.get()
        templates_on_page = scan_templates(text_page, template)
        if templates_on_page:
            logger.debug('Template in page ' + page.title())
        else:
            logger.debug('Not template in page ' + page.title())

def main():
    '''
    Main function that controls the whole execution.
    '''
    logger = initiate_logger()
    for cat, template in values.CATANDTEMPLATE.items():
        logger.debug('Initiating category ' + cat)
        logger.debug('with template ' + template)
        catgr = catlib.Category(wikipedia.Site("es", "wikipedia"), 
                              u"Category:%s" % cat)
        pages = pagegenerators.CategorizedPageGenerator(catgr, values.SUBCAT)
        for page in pages:
            act_on_page(logger, page, template)
                
if __name__ == '__main__':
    print 'Starting'
    main()
    print 'Ending'